/**
 * Created by admin on 2017/2/3.
 * 地图坐标分享功能实现
 */

var map = new BMap.Map("map");
var geo = new BMap.Geolocation();

var local = new BMap.LocalSearch(map, {
  // renderOptions: {map: map},
  onSearchComplete: function (results) {
    if (local.getStatus() == BMAP_STATUS_SUCCESS) {
      var s = [];
      for (var i = 0; i < results.getCurrentNumPois(); i++) {
        var poi = results.getPoi(i);
        s.push('<li data-point="' + poi.point.lng +'-'+ poi.point.lat + '">' + poi.title+'-'+poi.address + '</li>');
      }
      $('.search-list').html(s.join(''));
    }
  }
});

geo.getCurrentPosition(function (res) {
  var lat = res.point.lat;
  var lng = res.point.lng;
  var point = new BMap.Point(lng, lat);
  map.centerAndZoom(point, 16);
  info(lng, lat);
});

// 监听地图拖动事件
map.addEventListener("dragend", function () {
  var pointer = map.getCenter();
  info(pointer.lng, pointer.lat);
});

// 监听用户点击搜索
$('#search_btn').on('click', function () {
  var val = $.trim($('#search').val());
  if (!val) return;
  fetchEnd($('.search-list li').eq(0).get(0));
});

// 模糊搜索
$('.search-input').on('input keyup', function () {
  var val = $.trim(this.value);
  if (!val) {
    $('.search-list').hide();
    return;
  }
  local.search(val);
  $('.search-list').show();
});

// 监听用户点击搜索结果
$('.search-list').on('click', 'li', function () {
  $('.search-input').val(this.innerHTML);
  fetchEnd(this);
});

// 获取结果
var fetchEnd = function (ele) {
  $('.search-list').hide();
  var pointStr = $(ele).data('point').split('-');
  var lng = +pointStr[0];
  var lat = +pointStr[1];
  var point = new BMap.Point(lng, lat);
  map.centerAndZoom(point, 16);
  info(lng, lat);
};

// 获取地图信息
var info = function (lng, lat) {
  var point = new BMap.Point(lng, lat);
  var gc = new BMap.Geocoder();

  gc.getLocation(point, function (rs) {
    var list = [];
    list.push(['我的位置', rs.address]);

    if (rs.surroundingPois.length) {
      rs.surroundingPois.forEach(function (el) {
        list.push([el.title, $.trim(el.address) || el.title]);
      });
    }
    console.log(rs);

    renderData(list);
  });
}


// 渲染数据到页面
var renderData = function (list) {
  var html = [];
  list.forEach(function (el) {
    html.push('<li class="address-item"><p class="address-item-title">' +
        el[0] + '</p><span class="address-item-desc">' +
        el[1] + '</span></li>');
  });
  $('#list .address').html(html.join(''));
};

